import type { Dict } from '@/composables/types/dict'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useDictStore = defineStore('dict', () => {
  const dictMap = ref<Record<string, Dict[]>>({})

  const isLoading = ref<Record<string, boolean>>({})

  const getDict = async (dictKey: string, force: boolean = false) => {
    if (!dictKey) {
      throw new Error('dict key can not be null')
    }

    if (force || (!isLoading.value[dictKey] && !dictMap.value[dictKey])) {
      isLoading.value[dictKey] = true

      const res = await Apis.get('/system/dict/data/list', { params: { index: 1, limit: 100, dict_key: dictKey, status: 0 } })
      dictMap.value[dictKey] = res
      isLoading.value[dictKey] = false
    }
  }

  const clearDict = () => {
    dictMap.value = {}
    isLoading.value = {}
  }

  return {
    dictMap,
    clearDict,
    getDict,
  }
})
